"use client"

import React, {useState, useRef, useEffect, useContext} from 'react'
// @ts-ignore
import {LuckyGrid} from '@lucky-canvas/react'
import {draw, queryRaffleAwardList, tenDraw} from "@/apis";
import {RaffleAwardVO} from "@/types/RaffleAwardVO";

/**
 * 大转盘文档：https://100px.net/docs/grid.html
 * @constructor
 */
// @ts-ignore
export function LuckyGridPage({handleRefresh}) {
    const [lastPrizeIndex, setLastPrizeIndex] = useState<number | null>(null);
    const [lastDrawIsTen, setLastDrawIsTen] = useState(false);
    const [lastTen, setLastTen] = useState<any>(null);
    const [isDegraded, setIsDegraded] = useState(false);

    const [prizes, setPrizes] = useState([{}])
    const myLucky = useRef()

    const queryRaffleAwardListHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const userId = String(queryParams.get('userId'));
        const activityId = Number(queryParams.get('activityId'));
        const result = await queryRaffleAwardList(userId, activityId);
        const {code, info, data}: { code: string; info: string; data: RaffleAwardVO[] } = await result.json();

        if (code != "0000") {
            window.alert("获取抽奖奖品列表失败 code:" + code + " info:" + info)
            return;
        }

        // 创建一个新的奖品数组
        const prizes = [
            {
                x: 0,
                y: 0,
                fonts: [{text: data[0].awardTitle, top: '80%', fontSize: '12px', fontWeight: '800'}],
                imgs: [{src: "/raffle-award-00.png", width: "130px", height: "130px", activeSrc: "/raffle-award.png"}]
            },
            {
                x: 1,
                y: 0,
                fonts: [{text: data[1].awardTitle, top: '80%', fontSize: '12px', fontWeight: '800'}],
                imgs: [{src: "/raffle-award-01.png", width: "130px", height: "130px", activeSrc: "/raffle-award.png"}]
            },
            {
                x: 2,
                y: 0,
                fonts: [{text: data[2].awardTitle, top: '80%', fontSize: '12px', fontWeight: '800'}],
                imgs: [{src: "/raffle-award-02.png", width: "130px", height: "130px", activeSrc: "/raffle-award.png"}]
            },
            {
                x: 2,
                y: 1,
                fonts: [{text: data[3].awardTitle, top: '80%', fontSize: '12px', fontWeight: '800'}],
                imgs: [{src: "/raffle-award-12.png", width: "130px", height: "130px", activeSrc: "/raffle-award.png"}]
            },
            {
                x: 2,
                y: 2,
                fonts: [{
                    text: data[4].isAwardUnlock ? data[4].awardTitle : '再抽奖' + data[4].waitUnLockCount + '次解锁',
                    top: '80%',
                    fontSize: '12px',
                    fontWeight: '800'
                }],
                imgs: [{
                    src: data[4].isAwardUnlock ? "/raffle-award-22.png" : "/raffle-award-22-lock.png",
                    width: "130px",
                    height: "130px",
                    activeSrc: "/raffle-award.png"
                }]
            },
            {
                x: 1,
                y: 2,
                fonts: [{
                    text: data[5].isAwardUnlock ? data[5].awardTitle : '再抽奖' + data[5].waitUnLockCount + '次解锁',
                    top: '80%',
                    fontSize: '12px',
                    fontWeight: '800'
                }],
                imgs: [{
                    src: data[5].isAwardUnlock ? "/raffle-award-21.png" : "/raffle-award-21-lock.png",
                    width: "130px",
                    height: "130px",
                    activeSrc: "/raffle-award.png"
                }]
            },
            {
                x: 0,
                y: 2,
                fonts: [{
                    text: data[6].isAwardUnlock ? data[6].awardTitle : '再抽奖' + data[6].waitUnLockCount + '次解锁',
                    top: '80%',
                    fontSize: '12px',
                    fontWeight: '800'
                }],
                imgs: [{
                    src: data[6].isAwardUnlock ? "/raffle-award-20.png" : "/raffle-award-20-lock.png",
                    width: "130px",
                    height: "130px",
                    activeSrc: "/raffle-award.png"
                }]
            },
            {
                x: 0,
                y: 1,
                fonts: [{text: data[7].awardTitle, top: '80%', fontSize: '12px', fontWeight: '800'}],
                imgs: [{src: "/raffle-award-10.png", width: "130px", height: "130px", activeSrc: "/raffle-award.png"}]
            },
        ]

        // 设置奖品数据
        setPrizes(prizes)

    }

    const randomRaffleHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const userId = String(queryParams.get('userId'));
        const activityId = Number(queryParams.get('activityId'));

        let result = await draw(userId, activityId);
        const {code, info, data} = await result.json();
        if (code != "0000") {
            // 检查是否为降级状态
            if (code === "DEGRADE_SWITCH") {
                setIsDegraded(true);
                window.alert("系统已降级，请稍后再试");
                return null;
            }
            window.alert("随机抽奖失败 code:" + code + " info:" + info)
            return null;
        }
        setIsDegraded(false);
        setLastDrawIsTen(false);
        handleRefresh()
        // 为了方便测试，mock 的接口直接返回 awardIndex 也就是奖品列表中第几个奖品。
        const prizeIndex = data.awardIndex - 1;
        setLastPrizeIndex(prizeIndex); // 保存到 state
        return prizeIndex;
    }

    const [buttons] = useState([
        {
            x: 1,
            y: 1,
            background: "#7f95d1",
            shadow: '4',
            imgs: [{src: "/raffle-button.png", width: "130px", height: "130px"}]
        }
    ])

    // 调用十连随机抽奖
    const randomTenRaffleHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const userId = String(queryParams.get('userId'));
        const activityId = Number(queryParams.get('activityId'));
        const result = await tenDraw(userId, activityId);
        const {code, info, data} = await result.json();
        if (code != "0000") {
            // 检查是否为降级状态
            if (code === "DEGRADE_SWITCH") {
                setIsDegraded(true);
                window.alert("系统已降级，请稍后再试");
                return null;
            }
            window.alert("随机抽奖失败 code:" + code + " info:" + info)
            return null;
        }
        setIsDegraded(false);
        if (!Array.isArray(data) || data.length === 0) {
            throw new Error("返回的数据不是有效的数组或数组为空");
        }
        setLastDrawIsTen(true);
        setLastTen(data);
        // 设置最后一个奖品的索引，用于转盘动画
        const maxAwardIndex = Math.max(...data.map(item => item.awardIndex));
        setLastPrizeIndex(maxAwardIndex - 1);
        return data;
    }

    const [isLoading, setIsLoading] = useState(false);

    //  十连抽 button的handle
    const handleTenDraw = async () => {
        if(isLoading) return;
        setIsLoading(true);
        // 抽奖接口
        // @ts-ignore
        myLucky.current.play(); // 开始抽奖
        // 使用 setTimeout 模拟抽奖持续时间
        setTimeout(async () => {
            try {
                const data = await randomTenRaffleHandle();
                if (!data) {
                    // @ts-ignore
                    myLucky.current.stop();
                    return;
                }
                // @ts-ignore
                const maxAwardIndex = Math.max(...data.map(item => item.awardIndex));
                handleRefresh()
                // @ts-ignore
                myLucky.current.stop(maxAwardIndex-1);
            } finally {
                setIsLoading(false);
            }
        }, 300); // 抽奖持续时间，可以根据需要调整

        queryRaffleAwardListHandle().then(r => {
        });

    };

    const [defaultStyle] = useState([{background: "#b8c5f2"}])

    useEffect(() => {
        queryRaffleAwardListHandle().then(r => {
        });
    }, [])

    return <>
        <LuckyGrid
            ref={myLucky}
            width="400px"
            height="400px"
            rows="3"
            cols="3"
            prizes={prizes}
            defaultStyle={defaultStyle}
            buttons={buttons}
            onStart={() => { // 点击抽奖按钮会触发star回调
                // @ts-ignore
                myLucky.current.play()
                setTimeout(() => {
                    // 抽奖接口
                    randomRaffleHandle().then(prizeIndex => {
                            // @ts-ignore
                            myLucky.current.stop(prizeIndex);
                        }
                    );
                }, 100)
            }}
            onEnd={
                // @ts-ignore
                () => {
                    // 加载数据
                    queryRaffleAwardListHandle().then(r => {
                    });
                    // 如果系统已降级，不显示奖品信息
                    if (isDegraded) return;
                    // 展示奖品
                    if(lastDrawIsTen){
                        // 十连抽显示奖品
                        if (lastTen && lastTen.length > 0) {
                            // @ts-ignore
                            const prizeTitles = lastTen.map(prize => prize.awardTitle).join(', ');
                            alert('奖品列表【' + prizeTitles + '】');
                        }
                    }else{
                        // 单次抽奖显示奖品
                        if (lastPrizeIndex !== null && prizes.length > 0) {
                            const prize = prizes[lastPrizeIndex];
                            // @ts-ignore
                            alert('恭喜抽中奖品💐【' + prize.fonts[0].text + '】');
                        } else {
                            alert('未找到有效的奖品信息');
                        }
                    }

                }
            }>

        </LuckyGrid>
        {/* 添加十连抽按钮 */}
        <button
            style={{

                width: '400px',
                height: '80px',
                marginTop: '10px', // 可以根据需要调整上边距
                backgroundColor: '#4CAF50', // 按钮背景颜色
                color: 'white', // 字体颜色
                border: 'none', // 去掉边框
                borderRadius: '10px', // 圆角边框
                fontSize: '20px', // 字体大小
                cursor: 'pointer' // 鼠标样式
            }}
            onClick={handleTenDraw}
        >
            <img
                src="/ten-raffle-button.png"
                alt="十连抽按钮"
                style={{
                    width: '400px',  // 根据需求调整图片大小
                    height: '80px',
                }}
            />
        </button>
    </>

}